<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Requests;

use App\Models\Attachment;

/**
 * 附件模块表单请求验证
 * Class AttachmentRequest
 * @package App\Http\Requests
 */
class AttachmentRequest extends BaseRequest
{
    /**
     * 用户是否有权操作，true是，false否
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 字段验证规则
     *
     * @return array
     */
    public function rules()
    {
        return [
        ];
    }

    /**
     * 提示信息
     *
     * @return array
     */
    public function messages()
    {
        return [
        ];
    }

    /**
     * 定义场景
     *
     * @var \string[][]
     */
    public $scenes = [
    ];

    /**
     * 验证错误的自定义属性
     *
     * @return array
     */
    public function attributes()
    {
        return [
        ];
    }

    /**
     * 验证前
     *
     * @return void
     */
    protected function prepareForValidation()
    {
    }

    /**
     * 闭包验证规则：验证文件有效性
     * @param $attribute
     * @param $value // 附件id，多个文件以英文逗号隔开
     * @param $fail
     * @param $limit // 上传数量限制，0代表无限制
     * @return \Closure
     *
     *
     * 例：
     *    function ($attribute, $value, $fail) {
     *      return AttachmentRequest::validity($attribute, $value, $fail, $limit=0);
     *    }
     */
    public static function validity($attribute, $value, &$fail, $limit = 0)
    {
        if (!empty($value)) {
            $value_array = explode(',', $value);
            if ($limit > 0 && count($value_array) > $limit) {
                $fail($attribute . __('attachment.error_per_limit', ['number' => $limit]));
            }
            $attachment = Attachment::whereIn('id', $value_array)->pluck('id')->toArray();
            if (empty($attachment)) $fail($attribute . __('attachment.error_not_exists'));
            $error_flag = [];
            collect($value_array)->each(function ($item, $key) use ($attachment, &$error_flag, $fail) {
                if (!in_array($item, $attachment)) {
                    $error_flag[] = $key + 1;
                }
            });
            if (count($error_flag) == count($attachment)) {
                $fail($attribute . __('attachment.error_not_exists'));
            } else if (count($error_flag) > 0)
                $fail($attribute . __('attachment.error_position_not_exists', ['position' => join(',', $error_flag)]));
        }
    }
}
